<?php

use Biz\cache\brand\BrandBeLikedache;
use Biz\cache\brand\FineGoodsTest;
use Biz\model\GoodsTestActivity\FineGoodsJoinModel;
use Biz\model\GoodsTestActivity\FineGoodsJoinRecordModel;
use Biz\model\GoodsTestActivity\FineGoodsModel;
use Biz\model\GoodsTestActivity\FineGoodsMsgModel;
use Biz\service\GoodsTestActivity\FineGoodsService;
use Doraemon\cache\UserCounter;
use Doraemon\service\Follow;
use Doraemon\service\User;

/**
 *活动列表
 * Class ListAction
 */
class DetailsAction extends ActionPlugin
{
    public const USER_LEVEL = self::LEVEL_NOTHING;
    private const PAGE_SIZE = 20;

    /**
     * @throws Exception
     */
    public function main()
    {
        $id = $this->getRequest()->getPost('id', 0);
        $uid = $this->uid;
        if (!$id) {
            throw new \Exception('非法提交！');
        }
        //pv
        FineGoodsTest::hSetItem($id);
        //获取许愿消息列表
        $msg_list = $this->_getMsgList($id);
        //活动信息
        $data = $this->_getDetails($id);
        if (!$data) {
            throw new Exception("活动不存在！");
        }
        //获取品牌信息
        $brand_id = $data['brand_id'] ?? 0;
        $brand_uid = \Biz\model\brand\Brand::get('uid', ['id' => $brand_id]) ?: 0;
        $brand_counter = UserCounter::getOne($brand_uid);
        $user_like = BrandBeLikedache::getUserLike($brand_id);
        $user_like += ($brand_counter['beliked'] ?? 0) + ($brand_counter['befavorited'] ?? 0);
        $brand_counter['user_like'] = $user_like;
        $brand_info = User::getBrandCards([$brand_uid], $uid);
        $data['brand_info'] = $brand_info[$brand_uid] ?? [];
        $data['brand_info']['counter'] = $brand_counter;
        //许愿
        $data['msg_list'] = $msg_list ?? [];
        //获取活动报告
        $note = FineGoodsService::getNoteListById($id, $uid);
        $data['report_list'] = $note ? $note[$id] : [];
        //获取参与人列表
        $data['user_list'] = $this->_getUserList($id, $uid);

        //获取用户是否已经参加
        $joinRecordList = FineGoodsJoinRecordModel::all(['fine_goods_id' => $id], ['id', 'uid']);
        $is_join = false;
        $joinNum = 0;
        foreach ($joinRecordList as $row) {
            if ($row['uid'] == $uid) {
                $is_join = true;
            }
            $joinNum++;
        }
        $data['join_num'] = $data['beautify_num'] ? ($data['beautify_num'] + $joinNum) : $joinNum;

        if ($is_join && (int)$data['activity_state'] === FineGoodsModel::STATE_APPLYING) {
            $data['activity_state'] = FineGoodsModel::STATE_JOIN;
            $data['activity_state_name'] = "已申请";
        }

        $this->setSuccess($data);
    }

    /**
     * 活动信息
     * @param $id
     * @return array
     * @throws Exception
     */
    private function _getDetails($id): array
    {
        //获取详情
        $field = [
            'id',
            'type',
            'brand_id',
            'brand_name',
            'basic_id',
            'basic_title',
            'activity_title',
            'goods_num',
            'goods_worth',
            'goods_max_worth',
            'schedule_start_time',
            'schedule_end_time',
            'activity_state',
            'cover_img',
            'advantage_img',
            'advantage_text',
            'desc_text',
            'beautify_num',
            'report_num',
            'evaluation_id',
            'category_tag_id',
            'coupon_text'
        ];
        $details = FineGoodsModel::first(['id' => $id], $field);
        $details['count_down_time'] = $details['schedule_end_time'] + FineGoodsModel::VERIFY_USER_TIME;
        if (!$details) {
            throw new Exception("该活动不存在！");
        }
        unset($details['coupon_text']);

        $basic_id = $details['basic_id'];
        $wiki_id = \Biz\model\wiki\Wiki::getInfoByBasicId($basic_id, 'id');
        $details['wiki_id'] = $wiki_id;
        //获取感兴趣住友
        $details = FineGoodsService::getFineGoodsPv([$details], false);
        return $details ? $details[0] : [];
    }

    /**
     * 获取许愿消息列表
     * @param $id
     * @return array
     */
    private function _getMsgList($id): array
    {
        $where["LIMIT"] = self::PAGE_SIZE;
        $where['ORDER'] = ['addtime' => "DESC"];
        $where['fine_goods_id'] = $id;
        $where['msg_type'] = FineGoodsMsgModel::MSG_WISH;
        $msg_list = FineGoodsService::getMsgListByWhere($where, 'details');
        return $msg_list ?? [];
    }

    /**
     * 获取参与用户列表
     * @param $id
     * @param $uid
     * @return array
     */
    private function _getUserList($id, $uid): ?array
    {
        $user_list = [];
        $other_uids = FineGoodsJoinModel::getLastPersons($id, 'uid');
        if (!$other_uids) {
            return $user_list;
        }
        $follow_info = Follow::FollowStatus($uid, $other_uids);
        $user_info = User::getBatchBasicUserInfo($other_uids);
        $user_info = array_column($user_info, null, 'uid');

        foreach ($user_info as $k => $item) {
            $user_list[$k]['is_me'] = 0;
            if ($uid == (int)$item['uid']) {
                $user_list[$k]['is_me'] = 1;
            }
            $user_list[$k]['is_follow'] = $follow_info[$item['uid']] ?? 0;
            $user_list[$k]['uid'] = $item['uid'] ?? 0;
            $user_list[$k]['nick'] = $item['nick'] ?? '';
            $user_list[$k]['avatar'] = $item['avatar'] ?: $item['small_avatar'];
        }
        return array_values($user_list);

    }

}


